package com.aizhixin.lab.project.course.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.ExcelUtil;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.entity.User;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.project.course.domain.ProjectEvaluatingaTableDomain;
import com.aizhixin.lab.project.course.domain.ProjectPeopleEvaluatingDomain;
import com.aizhixin.lab.project.course.domain.ProjectPeopleEvaluatingListDomain;
import com.aizhixin.lab.project.course.domain.QueryProjectReplyDomain;
import com.aizhixin.lab.project.course.entity.ProjectClassStu;
import com.aizhixin.lab.project.course.entity.ProjectGroupTask;
import com.aizhixin.lab.project.template.domain.*;
import com.aizhixin.lab.project.course.entity.ProjectPeopleEvaluating;
import com.aizhixin.lab.project.course.repository.ProjectPeopleEvaluatingRepository;
import com.aizhixin.lab.project.course.service.ProjectPeopleEvaluatingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@RequestMapping("/api/v1/project/peopleEvaluating")
@RestController
@Api(value = "项目评测", tags = "项目评测")
public class ProjectPeopleEvaluatingController {
    @Autowired
    private ProjectPeopleEvaluatingService projectPeopleEvaluatingService;
    @Autowired
    private ProjectPeopleEvaluatingRepository projectPeopleEvaluatingRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private Config config;

    @RequestMapping(value = "/importEvaluating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "文件导入", httpMethod = "POST", notes = "文件导入<br><br><b>@author lwq</b>")
    public ResponseEntity<?> importEvaluating(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "projectId") @RequestParam(value = "projectId") String projectId,
                                              @ApiParam(value = "releaseProjectReplyId") @RequestParam(value = "releaseProjectReplyId") String releaseProjectReplyId,
                                              @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        projectPeopleEvaluatingService.importEvaluating(file,releaseProjectReplyId, projectId, account.getId());
        result.put(ApiReturnConstants.SUCCESS, true);

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/exportEvaluating", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "测评维度导出", httpMethod = "GET", notes = "测评维度导出<br><br><b>@author lwq</b>")
    public ResponseEntity<?> exportEvaluating(@RequestHeader("Authorization") String token,
                                              @ApiParam(value = "projectId") @RequestParam(value = "projectId") String projectId
            , HttpServletResponse response) throws IOException {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        HSSFWorkbook wb = projectPeopleEvaluatingService.exportEvaluating(projectId);
        FileOutputStream output = new FileOutputStream(config.getBaseDir() + "/vid.xls");
        wb.write(output);
        output.flush();
        String basePath = config.getBaseDir() + "/vid.xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存", httpMethod = "POST", notes = "保存/编辑<br><br><b>lwq</b>")
    public ResponseEntity<?> save(@RequestHeader("Authorization") String token, @RequestBody ProjectPeopleEvaluatingListDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        projectPeopleEvaluatingService.save(domain);
        result.put(ApiReturnConstants.SUCCESS, true);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/isEvaluating", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询是否存在测评维度", httpMethod = "GET", notes = "查询是否存在测评维度")
    public ResponseEntity<?> isEvaluating(@RequestHeader("Authorization") String token, @RequestParam(name = "releaseProjectReplyId") String releaseProjectReplyId) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<ProjectPeopleEvaluating> peopleEvaluating = projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlag(releaseProjectReplyId, 0);
        if (peopleEvaluating.size() > 0) {
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findEvaluating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "测评维度查询", httpMethod = "POST", notes = "测评维度查询")
    public ResponseEntity<?> findEvaluating(@RequestHeader("Authorization") String token, @RequestBody BaseQueryDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            List<ProjectPeopleEvaluating> peopleEvaluating = null;
            if (StringUtils.isEmpty(domain.getReleaseProjectReplyId())) {
                if (domain.getAct0n() == null) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlag(domain.getProjectId(), DataValidity.VALID.getState());
                } else if (domain.getAct0n() == 0) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlagAndType(0 + "", 0, domain.getType());
                } else if (domain.getAct0n() == 1) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlagAndType(domain.getProjectId(), 0, domain.getType());
                }
            } else {
                if (domain.getAct0n() == null) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlag(domain.getReleaseProjectReplyId(), DataValidity.VALID.getState());
                } else if (domain.getAct0n() == 0) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlagAndType(0 + "", 0, domain.getType());
                } else if (domain.getAct0n() == 1) {
                    peopleEvaluating = projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlagAndType(domain.getReleaseProjectReplyId(), 0, domain.getType());
                }
            }
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, peopleEvaluating);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/findEvaluatingTableHade", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "测评个人维度表头查询", httpMethod = "POST", notes = "测评个人维度表头查询")
    public ResponseEntity<?> findEvaluatingTableHade(@RequestHeader("Authorization") String token, @RequestBody QueryProjectReplyDomain domain) {
        AccountDTO account = accountService.getUserByToken(token);
        Map<String, Object> result = new HashMap<String, Object>();
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        try {
            List<ProjectEvaluatingaTableDomain> peopleEvaluating = projectPeopleEvaluatingService.findEvaluatingTableHade(domain);
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, peopleEvaluating);
        } catch (Exception e) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, e.getMessage());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


}
